package com.zoke.daycarpool.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.umeng.analytics.MobclickAgent;
import com.zoke.daycarpool.R;
import com.zoke.daycarpool.adapter.CarpoolAdapter;
import com.zoke.daycarpool.base.BaseAppFragment;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.CarpoolConfig.MessageCode;
import com.zoke.daycarpool.config.CarpoolConfig.ShareKey;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.domain.DayCarpool;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.domain.UserInstense;
import com.zoke.daycarpool.parser.MainParser;
import com.zoke.daycarpool.ui.Channels;
import com.zoke.daycarpool.ui.Filtrate;
import com.zoke.daycarpool.util.LogTest;
import com.zoke.daycarpool.view.PullToRefreshLayout;
import com.zoke.daycarpool.view.PullToRefreshLayout.OnRefreshListener;
import com.zoke.daycarpool.view.PullableListView;
import com.zoke.support.floatingmenu.FloatingItem;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeErro;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.utils.CommonUtil;
import com.zoke.support.utils.PersistTool;
import com.zoke.support.view.ZokeToast;

/**
 * 首页-- ⇌ ⇋
 * 
 * @author jack
 * 
 */
public class MainFragment extends BaseAppFragment implements OnRefreshListener {
	private CarpoolAdapter mAdapter;
	private List<FloatingItem> mMenuList = new ArrayList<FloatingItem>();//
	private UserBeen mUser;
	private PullToRefreshLayout mPullContainer;
	private PullableListView mListView;

	private String mLastId;//

	private boolean isTaker;

	// --筛选条件
	private int mTarget;
	private int mDist;
	private int mTime;
	private String mLat;
	private String mLng;

	private String mChannelName;//
	private String mChannelId;//

	public static final String ChannelNameForStart = "keyForChannelNameforstart";
	public static final String ChannelNameForEnd = "keyForChannelNameforend";
	public static final String ChannelId = "keyForChannelId";
	public static final String startCityCode = "cityCodeforstart";
	public static final String endCityCode = "cityCodeforEnd";

	/** 数据 **/
	private List<DayCarpool> mList = new ArrayList<DayCarpool>();
	private View netFaileView;

	@Override
	protected void onCreateView(Bundle savedInstanceState) {
		super.onCreateView(savedInstanceState);
		setContentView(R.layout.fragment_main);
		mUser = UserInstense.getInstense(getActivity()).getUser();
		isTaker = mUser.getIdentify().equals("1");
		mChannelName = PersistTool.getString(ChannelNameForStart, "北京") + ""
				+ CarpoolConfig.ROADARROW + ""
				+ PersistTool.getString(ChannelNameForEnd, "香河");
		mChannelId = PersistTool.getString(ChannelId, "1");
		mLat = PersistTool.getString(ShareKey.LAT, "-1");
		mLng = PersistTool.getString(ShareKey.LON, "-1");
		// 默认路线名字及Id
		mtiManager.setTitle("" + mChannelName);
		mtiManager.setTitleIcon(R.drawable.main_arrow_down);
		netFaileView = findViewById(R.id.netfailed_Container);
		// mtiManager.setLeftIcon(R.drawable.add);
		mtiManager.setRightIcon(R.drawable.filter);// add去了
		mAdapter = new CarpoolAdapter(getActivity(), mList, isTaker);
		findView();
		doEvent();
		// mPullMenu = new PullMenu(getActivity(), mMenuList);
		mListView.setAdapter(mAdapter);
		mLastId = "";
		if (CommonUtil.getNetWorkStates(getActivity())) {
			netFaileView.setVisibility(View.GONE);
			mPullContainer.setVisibility(View.VISIBLE);
			fetchMainList();
		} else {
			// 更新暂无网络界面
			netFaileView.setVisibility(View.VISIBLE);
			mPullContainer.setVisibility(View.GONE);
		}
	}

	/** 获取首页list **/
	private void fetchMainList() {
		ZokeParams param = CarpoolParamStore.getDefaultParam(mHashCode);
		param.setUrl(UrlBank.doMainList);
		param.put("chId", mChannelId);
		if (!TextUtils.isEmpty(mLastId))
			param.put("timestamp", mLastId);
		if (mTarget != 0)
			param.put("target", "" + mTarget);// 可选 去北京 去香河
		if (mDist != 0)
			param.put("dist", "" + mDist);// 可选 1km 2km
		if (mTime != 0)
			param.put("startTime", "" + mTime);// 可选 今天 明天
		if (!mLat.equals("-1")) {
			param.put("lon", "" + mLng);
			param.put("lat", "" + mLat);
		}
		// 少个参数
		param.put("sid", "" + mUser.getUserId());
		HttpStores.getInstense(getActivity()).get(param);
	}

	// // 测试menu
	// private void textMenu() {
	// for (int x = 0; x < 5; x++) {
	// FloatingItem item = new FloatingItem();
	// item.setType(FloatingItemType._PARENT);
	// mMenuList.add(item);
	// if (x == 0) {
	// item.setSelected(true);
	// }
	// }
	// }

	@Override
	protected void handleMsg(Message msg) {
		super.handleMsg(msg);
		// 处理发消息 -------
		int id = msg.what;
		if (id == MessageCode.REUPDATE_MAIN) {
			// mListView.autoRefresh();
			return;
		}

		if (id == MessageCode.UPDATE_MIENFRAGMENT) {
			mLastId = "";
			mUser = UserInstense.getInstense(getActivity()).getUser();
			isTaker = mUser.getIdentify().equals("1");
			fetchMainList();
			return;
		}

	}

	@Override
	protected void findView() {
		mPullContainer = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		mListView = (PullableListView) findViewById(R.id.content_view);
	}

	@Override
	protected void doEvent() {
		// mListView.setXListViewListener(this);
		mPullContainer.setOnRefreshListener(this);
		netFaileView.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
		case R.id.netfailed_Container:
			netFaileView.setVisibility(View.GONE);
			mPullContainer.setVisibility(View.VISIBLE);
			fetchMainList();
			break;

		default:
			break;
		}
	}

	@Override
	public void onTitleClick(View view) {
		super.onTitleClick(view);
		// if (mPullMenu == null)
		// return;
		// mPullMenu.showAsDropDown(mtiManager.getTitleContainer());
		mIntent = new Intent(getActivity(), Channels.class);
		startUIForResult(mIntent, 11);
	}

	@Override
	public void onTitleClickLeft(View view) {
		// mIntent = new Intent(getActivity(), Channels.class);
		// startUI(mIntent);
	}

	@Override
	public void onTitleClickRight(View view) {
		super.onTitleClickRight(view);
		mIntent = new Intent(getActivity(), Filtrate.class);
		mIntent.putExtra(Filtrate.KeyToBJ, mTarget);
		mIntent.putExtra(Filtrate.keyDest, mDist);
		mIntent.putExtra(Filtrate.keyDay, mTime);
		startUIForResult(mIntent, 11);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		if (resultCode == Filtrate.filtrateResult) {
			// 过滤返回结果
			mTarget = data.getIntExtra(Filtrate.KeyToBJ, 0);
			mDist = data.getIntExtra(Filtrate.keyDest, 0);
			mTime = data.getIntExtra(Filtrate.keyDay, 0);
			LogTest.m("返回结果=" + mTarget + mDist + mTime);
			return;
		}

		if (resultCode == Channels.resultChannel) {
			mChannelId = data.getStringExtra(Channels.channelId);
			mChannelName = data.getStringExtra(Channels.channelNameForStart)
					+ CarpoolConfig.ROADARROW + ""
					+ data.getStringExtra(Channels.channelNameForEnd);
			mtiManager.setTitle("" + mChannelName);
			//
			mList.clear();
			mAdapter.notifyDataSetChanged();
			mLastId = "";
			fetchMainList();
			return;
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("MainScreen"); // 统计页面
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("MainScreen");
	}

	/** 是否刷新 **/
	private boolean isRefresh() {
		return TextUtils.isEmpty(mLastId);
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		String resuString = (String) out.getResult();
		LogTest.tag("result=" + resuString);
		MainParser parser = new MainParser();
		try {
			List<DayCarpool> list = parser.parseJson(resuString);
			if (list == null || list.size() == 0) {
				// 不再继续
				if (!isRefresh()) {
					ZokeToast.show(getActivity(), "没有更多数据了");
				}
				mPullContainer.refreshFinish();
				mPullContainer.loadmoreFinish();
				mAdapter.setTaker(isTaker);
				return;
			}

			if (isRefresh()) {
				mList.clear();
			}

			if (list != null && list.size() != 0) {
				mList.addAll(list);
				if (isRefresh()) {
					DayCarpool dc = list.get(0);
					PersistTool.saveString(CarpoolConfig.MAINTIMESTAMPID,
							dc.getMsgId() + "");
				}
				DayCarpool dc = list.get(list.size() - 1);
				mLastId = dc.getMsgId() + "";
			}
			mAdapter.setTaker(isTaker);
			mAdapter.notifyDataSetChanged();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mPullContainer.refreshFinish();
		mPullContainer.loadmoreFinish();
	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeErro erro = (ZokeErro) out.getResult();
		LogTest.tag("erro=" + erro);
		mPullContainer.refreshFinish();
		mPullContainer.loadmoreFinish();
		ZokeToast.showNetFailed(getActivity());
		if (!CommonUtil.getNetWorkStates(getActivity())) {
			netFaileView.setVisibility(View.VISIBLE);
			mPullContainer.setVisibility(View.GONE);
		}
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		mLastId = "";
		fetchMainList();
	}

	@Override
	public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
		fetchMainList();
	}
}
